<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="气压" prop="airPressure">
        <el-input
          v-model="queryParams.airPressure"
          placeholder="请输入气压"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="水压" prop="waterPressure">
        <el-input
          v-model="queryParams.waterPressure"
          placeholder="请输入水压"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="水流量" prop="waterFlow">
        <el-input
          v-model="queryParams.waterFlow"
          placeholder="请输入水流量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="气流量" prop="airFlow">
        <el-input
          v-model="queryParams.airFlow"
          placeholder="请输入气流量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采集时间" prop="importDay">
        <el-date-picker clearable
          v-model="queryParams.importDay"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择采集时间">
        </el-date-picker>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleDownloadTemplate">下载模板</el-button>
        <el-button type="success" icon="el-icon-upload" size="mini" @click="handleOpenImport">导入</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column label="气压" align="center" prop="airPressure" />
      <el-table-column label="水压" align="center" prop="waterPressure" />
      <el-table-column label="水流量" align="center" prop="waterFlow" />
      <el-table-column label="气流量" align="center" prop="airFlow" />
      <el-table-column label="采集时间" align="center" prop="importDay" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.importDay, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="180" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:data:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入弹窗 -->
    <el-dialog title="导入压力流量数据" :visible.sync="importOpen" width="500px" append-to-body>
      <el-form ref="importForm" :model="importForm" label-width="120px">
        <el-form-item label="项目日期" prop="importDay">
          <el-select v-model="importForm.importDay" placeholder="请选择项目日期" @change="handleExperimentDateChange">
            <el-option v-for="item in experimentDates" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围" prop="timeRange">
          <el-select v-model="importForm.timeRange" placeholder="请选择时间范围">
            <el-option v-for="item in experimentTimeRanges" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择文件" prop="file">
          <el-upload ref="upload" :auto-upload="false" :file-list="fileList" :on-change="handleFileChange" :limit="1">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport">确 定</el-button>
        <el-button @click="importOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listData, getData, delData } from "@/api/businessInfo/flowData";
import request from "@/utils/request";

export default {
  name: "Data",
  data() {
    return {
      loading: true,
      total: 0,
      dataList: [],
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        airPressure: null,
        waterPressure: null,
        waterFlow: null,
        airFlow: null,
        collectTime: null,
      },
      ids: [],
      single: true,
      multiple: true,

      // 导入
      importOpen: false,
      importForm: {
        importDay: null,
        timeRange: null,
        file: null
      },
      fileList: [],
      experimentDates: [],
      experimentTimeRanges: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listData(this.queryParams).then(res => {
        this.dataList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },

    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置搜索 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },

    /** 多选框 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 删除 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(`是否确认删除压力流量数据编号为"${ids}"的数据项？`).then(() => {
        return delData(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 下载模板 */
    handleDownloadTemplate() {
      const type = this.queryParams.type;
      request({
        url: `/business/flowData/downloadTemplate?type=${type}&ts=${Date.now()}`,
        method: 'get',
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res]);
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.setAttribute('download', `PV特性导入模版_${new Date().getTime()}.xlsx`);
        document.body.appendChild(link);
        link.click();
        link.remove();
        window.URL.revokeObjectURL(link.href);
      });
    },


    /** 打开导入弹窗 */
    handleOpenImport() {
      this.importOpen = true;
      this.importForm = { importDay: null, timeRange: null, file: null };
      this.fileList = [];

      request({ url: "/business/project/experimentTimes", method: "get" }).then(res => {
        this.experimentDates = res.data;
      });
    },

    /** 项目日期变化 */
    handleExperimentDateChange(val) {
      this.importForm.timeRange = null;
      this.experimentTimeRanges = [];
      request({
        url: "/business/project/experimentTimeRangesByDate",
        method: "get",
        params: { experimentDate: val }
      }).then(res => {
        this.experimentTimeRanges = res.data.map(item => ({
          label: `${item.startTime}-${item.endTime}`,
          value: `${item.startTime}-${item.endTime}`
        }));
      });
    },

    /** 文件选择 */
    handleFileChange(file) {
      this.importForm.file = file.raw;
      this.fileList = [file];
    },

    /** 提交导入 */
    submitImport() {
      if (!this.importForm.importDay || !this.importForm.timeRange || !this.importForm.file) {
        this.$modal.msgError("请完整填写导入信息");
        return;
      }
      const [startTime, endTime] = this.importForm.timeRange.split("-");
      const formData = new FormData();
      formData.append("importDay", this.importForm.importDay);
      formData.append("startTime", startTime);
      formData.append("endTime", endTime);
      formData.append("file", this.importForm.file);

      request({
        url: "/business/flowData/importData",
        method: "post",
        data: formData,
        headers: { "Content-Type": "multipart/form-data" }
      }).then(() => {
        this.$modal.msgSuccess("导入成功");
        this.importOpen = false;
        this.getList();
      });
    },

    /** 工具：时间格式化 */
    parseTime(time, format) {
      if (!time) return '';
      const date = new Date(time);
      const o = {
        y: date.getFullYear(),
        m: String(date.getMonth() + 1).padStart(2, '0'),
        d: String(date.getDate()).padStart(2, '0')
      };
      return format.replace('{y}', o.y).replace('{m}', o.m).replace('{d}', o.d);
    }
  }
};
</script>
